//
//  ViewController.swift

import UIKit
import Foundation

class ViewController: UIViewController,UITextFieldDelegate,UISearchBarDelegate,UITableViewDelegate, UITableViewDataSource {
    @IBOutlet var tableView:UITableView?
    var def = UserDefaults()
    var nowUrl = ""
    var listArr:Array? = ["http://wechat.canseq.com/react/index.html"]
    lazy var searchBar:UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width-self.view.frame.size.width*0.21, height: 44))
    
    lazy var qdCodeButton:UIButton = UIButton(type: UIButtonType.system)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        def.setValue(listArr, forKey: "list")
        if((def.array(forKey: "list") == nil)) {
            def.setValue(listArr, forKey: "list")
        } else {
            listArr = def.array(forKey: "list") as! Array<String>?
            nowUrl = listArr![0]
            gotoApp(str: nowUrl, isAddlist: false)
        }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTapSelector(_:)))
        view.addGestureRecognizer(tapGesture)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.rowHeight = 70
        
        searchBar.placeholder = "输入一个网址"
        searchBar.keyboardType = UIKeyboardType.URL
        searchBar.autocapitalizationType = UITextAutocapitalizationType.none
        searchBar.returnKeyType = UIReturnKeyType.go
        searchBar.delegate = self
        let leftNavBarButton = UIBarButtonItem(customView: searchBar)
        self.navigationItem.leftBarButtonItem = leftNavBarButton
        
        qdCodeButton.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width*0.08, height: 44)
        qdCodeButton.setTitle("扫码", for: .normal)
        qdCodeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        qdCodeButton.addTarget(self, action: #selector(gotoQdCode), for: .touchUpInside)
        let rightNavBarButton = UIBarButtonItem(customView: qdCodeButton)
        self.navigationItem.rightBarButtonItem = rightNavBarButton
    }
    override func viewWillAppear(_ animated: Bool) {
        listArr = def.array(forKey: "list") as! Array<String>?
        tableView?.reloadData()
    }
    func handleTapSelector(_ sender: UITapGestureRecognizer){
        if (sender.state == .ended) {
            searchBar.endEditing(true)
        }
        sender.cancelsTouchesInView = false
    }
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        nowUrl = searchBar.text!
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        nowUrl = searchBar.text!
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.endEditing(true)
        nowUrl = searchBar.text!
        gotoApp(str: nowUrl, isAddlist: true)
    }
    func gotoApp(str:String, isAddlist:Bool){
        if(str.characters.count < 3) {return}
        if(isAddlist) {
            listArr?.insert(str, at: 0)
            def.setValue(listArr, forKey: "list")
        }
        let web = WKWebViewController()
        var url = str
        if(str.range(of: "http") == nil){
            url = "http://"+str
        }
        web.loadUrlSting(string: url)
        web.isNavHidden = true
        navigationController?.pushViewController(web, animated: isAddlist)
    }
    func gotoQdCode(){
        let qdcodeVC = QRViewController()
        navigationController?.pushViewController(qdcodeVC, animated: true)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listArr!.count+1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "cell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
        if(cell == nil) {
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellid)
            cell?.selectionStyle = UITableViewCellSelectionStyle.default
        }
        
        if(indexPath.row < listArr!.count) {
            cell!.textLabel?.text = listArr?[indexPath.row]
        }
        else if(indexPath.row == listArr!.count) {
            if(indexPath.row != 0) {
                cell!.textLabel?.text = "清空列表"
            } else {
                cell?.textLabel?.text = ""
            }
        }
        return cell!
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        tableView.deselectRow(at: indexPath, animated: true)
        if(indexPath.row < listArr!.count) {
            nowUrl = listArr![indexPath.row]
            gotoApp(str: nowUrl, isAddlist: false)
        }
        else if(indexPath.row == listArr!.count) {
            listArr = []
            def.set(listArr, forKey: "list")
            tableView.reloadData()
        }
    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        if(indexPath.row == listArr!.count) {
            return UITableViewCellEditingStyle.none
        }
        return UITableViewCellEditingStyle.delete
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除历史"
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
            listArr?.remove(at: indexPath.row)
            def.setValue(listArr, forKey: "list")
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
        }
    }
}

